package com.samphanie.security.security.component;

import cn.hutool.core.util.URLUtil;
import com.samphanie.common.constants.SystemConstants;
import com.samphanie.security.config.IgnoreUrlsConfig;
import com.samphanie.security.security.authorization.AuthorizationDecisionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @Description: 动态权限过滤器，用于实现基于路径的动态权限过滤
 * @Author ZSY
 * @createTime 2021/8/31 13:17
 */
@Slf4j
@Component
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {
    @Resource
    private DynamicSecurityMetadataSource dynamicSecurityMetadataSource;
    @Resource
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Resource
    public void setMyAccessDecisionManager(AuthorizationDecisionManager authorizationDecisionManager) {
        super.setAccessDecisionManager(authorizationDecisionManager);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);

        // OPTIONS请求直接放行
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }

        String uri = request.getRequestURI();
        String path = URLUtil.getPath(uri);
        // 白名单请求直接放行
        AntPathMatcher pathMatcher = new AntPathMatcher();
        List<String> urls = ignoreUrlsConfig.getUrls();
        for (String url : urls) {
            if (pathMatcher.match(url, path)) {
                fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
                return;
            }
        }
//        String token = request.getHeader(SystemConstants.JWT_TOKEN_HEADER);
//        if (StrUtil.isEmpty(token)) {
//            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
//            return;
//        }
        // 非管理端路径直接放行
        if (!pathMatcher.match(SystemConstants.ADMIN_URL_PATTERN, uri)) {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }

        // 此处会调用AccessDecisionManager中的decide方法进行鉴权操作
        InterceptorStatusToken invocation = super.beforeInvocation(fi);
        try {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(invocation, null);
        }
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return dynamicSecurityMetadataSource;
    }

    @Override
    public void destroy() { }
}
